from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import News, User, Comment
from info.response_code import RET
from utils.common import user_login_data
from . import news_blu


# 新闻详情
# URL：动态/int:news_id
# 请求方式：GET
@news_blu.route('/<int:news_id>')
@user_login_data
def get_detail_news(news_id):
    # 一、用户信息
    user = g.user

    # 二、点击排行
    # 2.1查询数据库
    try:
        news_model_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not news_model_list:
        return jsonify(errno=RET.DBERR, errmsg="没有数据")
    # 2.2模型列表    # 2.3模型转字典# 2.4拼接到data中
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())

    # 三、详情显示
    # 3.1 查询数据库
    try:
        detail_model_list = News.query.filter(News.id == news_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "查询数据库失败")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "查询数据库失败")

    # 3.2 将数据模型转化为数据字典的列表
    detail_dict_li = detail_model_list.to_dict()

    # 四、显示新闻的收藏状态
    is_collected = False
    # 递进判断：1、用户是否登陆;2、是否收藏
    if user:
        if news in user.collection_news:
            is_collected = True

    # 五、显示新闻的评论
    comment_list = []
    if user:
        comment_model = Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()

        if comment_model:
            for item in comment_model:
                comment_dict = item.to_dict()
                comment_list.append(comment_dict)


    data = {
        'user': user.to_dict() if user else None,
        'news_dict_li': news_dict_li,
        'detail_dict_li':detail_dict_li,
        'is_collected':is_collected,
        'comments':comment_list
    }
    return render_template('news/detail.html',data = data)


"""
请求方式：POST
URL：/news_collect
传参方式：JSON
参数：news_id, action
"""
@news_blu.route('/news_collect',methods=(['POST']))
@user_login_data
def news_collect():
    # 1、判断是否登陆
    user = g.user
    if not user:
        return jsonify(errno = RET.SESSIONERR,errmsg="用户未登陆")

    # 2、获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 3、校验参数(参数齐全，news_id是否是整形，新闻是否存在，action是否合法）
    if not all([news_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数不全")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg="参数错误")

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "查询数据库失败")

    if not news:
        return jsonify(errno = RET.DBERR,errmsg = "未查询到相关数据")

    # 4、逻辑处理（两种情景：收藏、取消收藏）
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    # 5、返回数据
    return jsonify(errno = RET.OK, errmsg = '成功')


"""
请求方式：POST
URL：/news_comment
传参方式：JSON
参数：news_id, comment, parent_id
"""
@news_blu.route('/news_comment',methods=(['POST']))
@user_login_data
def add_news_comment():
    # 1、判断登陆状态
    user = g.user
    # comments=g.comments
    if not user:
        return jsonify(errno = RET.SESSIONERR,errmsg = "用户未登陆")

    # 2、获取参数
    news_id = request.json.get('news_id')
    comment_str = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    # 3、校验参数(齐全、news_id类型、是否存在news、如果传了parent_id判断类型）
    if not all([news_id,comment_str]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不齐全")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg ="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "查询数据库失败")

    if parent_id:
        try:
            parent_id = int(parent_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


    # 4、逻辑处理(创建comment模型类，添加评论数据，子评论处理）
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news.id
    comment.content = comment_str

    if parent_id:
        comment.parent_id = parent_id

    # 提交数据
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = "数据库提交错误")
    comment = comment.to_dict()
    # 5、返回数据
    return jsonify(errno = RET.OK, errmsg = "成功",data =comment)
